package com.itrui.order.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itrui.feign.client.PictureClient;
import com.itrui.feign.client.ProductClient;
import com.itrui.feign.client.pojo.Product;
import com.itrui.order.common.Code;
import com.itrui.order.common.Result;
import com.itrui.order.pojo.MyCollocation;
import com.itrui.order.service.MyCollocationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/collection")
public class CollectionController {

    @Autowired
    private MyCollocationService collectionService;

    @Autowired
    private ProductClient productClient;

    /**
     * 收藏商品
     * @param myCollection
     * @return
     */
    @PostMapping
    public Result addCollecton(@RequestBody MyCollocation myCollection){

        myCollection.setCreateTime(LocalDateTime.now());
        boolean b = collectionService.save(myCollection);

        return b?new Result(Code.SAVE_OK,"收藏成功"):new Result(Code.SAVE_ERR,"收藏失败");
    };

    /**
     * 获取用户收藏
     * @param uid
     * @return
     */
    @GetMapping("/{uid}")
    public Result selectCollecton(@PathVariable Long uid ){
        LambdaQueryWrapper<MyCollocation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MyCollocation::getUserId,uid);
        List<MyCollocation> list = collectionService.list(queryWrapper);
        list = list.stream().map((item)->{
            Long productId = item.getProductId();
            Product productById = productClient.getProductById(productId);
            item.setProduct(productById);
            return item;
        }).collect(Collectors.toList());
        return new Result(Code.GET_OK,list);
    };

    /**
     * 取消收藏
     * @param id
     * @param uid
     * @return
     */
    @DeleteMapping("/{id}/user/{uid}")
    public Result delectCollection(@PathVariable Long id ,@PathVariable Long uid ){

        System.out.println("商品id：" + id);
        System.out.println("用户id：" + uid);

        LambdaQueryWrapper<MyCollocation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MyCollocation::getUserId, uid).eq(MyCollocation::getId,id);
        boolean remove = collectionService.remove(queryWrapper);

        return remove?new Result(Code.DELETE_OK,"删除成功"):new Result(Code.DELETE_ERR,"删除失败");

    };

}
